var SDK = require('../sdk/NIM_Web_SDK_v5.0.0.js')
import cache from './cache.js'
import utils from './util.js'
var userInfo = wx.getStorageSync('userInfo')
var loginportschangeShow = false
// import userInfo from '../pages/message/modelUserInfo.js'
var defOptions = {
  onConnect: function () {
    console.log('连接成功');
    wx.hideLoading();
    if (cache.get('_navigate_place') == 'kf') {
      cache.set('_navigate_place') == ''
      wx.navigateTo({
        url: '../../message/chat/chat' // 不带id为客服
      })
    }
  },
  onWillReconnect: function(obj) {
    // 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
    console.log('即将重连');
    console.log(obj.retryCount);
    console.log(obj.duration);
  },
  onloginportschange: function(loginPorts) { // 多端登陆 需求确定.TODO
    if (loginportschangeShow) return
    if (loginPorts && loginPorts.length > 0) {
      var arr = loginPorts.filter(it => {
        return (it.type == 'Android' || it.type == 'iOS')
      })
      if (arr.length > 0) {
        var time = utils.parseTime(arr[0].time, '{y}-{m}-{d} {h}:{i}:{s}')
        wx.showModal({
          title: '提示',
          content: `您的账号于${time}在其他手持设备登陆,如非本人操作,请及时修改密码!如需修改,请到App修改密码`,
          showCancel: false,
          cancelColor: '#4121C4',
          confirmText: '知道了',
          // cancelText: '取消',
          success: function(res) {
            loginportschangeShow = true
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
    console.log('当前登录帐号在其它端的状态发生改变了', loginPorts);
  },
  onDisconnect: function (error) {
    cache.set('_team_list', []);
    // 此时说明 SDK 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
    console.log('丢失连接');
    wx.showToast({title: error.message,icon: 'none'});
    wx.reLaunch({
      url: '/pages/home/main/main'
    })
    console.log(error);
    if (error) {
      switch (error.code) {
        // 账号或者密码错误, 请跳转到登录页面并提示错误
        case 302:
          break;
        // 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
        case 417:
          break;
        // 被踢, 请提示错误后跳转到登录页面
        case 'kicked':
          break;
        default:
          break;
      }
    }
  },
  onError: function (error) {
    console.log(error);
  },
  onMsg: function (msg) {
    console.log('收到消息',msg);
    if (msg.from == '0000') return
    // 电话结束通知
    if (msg.type == 'custom' && msg.content) {
      var contents = JSON.parse(msg.content)
      if (contents.type == 20 || contents.type == 21) {
        wx.eventBus.trigger('_phone_end', msg.sessionId)
      }
    }
    let wholeSession = wx.getStorageSync(msg.sessionId)
    if (wholeSession) {
      let obj = (wholeSession && wholeSession.msgs) || {}
      let newMsgList = wx.nim.mergeMsgs(obj, msg)
      wholeSession.msgs = newMsgList
      wx.setStorageSync(msg.sessionId, wholeSession) // 更新store
    } else {
      
    }
    console.log('更新了')
    // pushMsg(msg);
    switch (msg.type) {
      case 'custom':
        // onCustomMsg(msg);
        break;
      case 'notification':
        // 处理群通知消息
        // onTeamNotificationMsg(msg);
        break;
      case 'image': // 图片
        try {
          wx.eventBus.trigger('receive_img', {msg: msg})
        } catch(e) {

        }
        break
      case 'text': // 文字
        console.log('触发了没？')
        try {
          wx.eventBus.trigger('receive_msg', {msg: msg})
        } catch (e) {

        }
        break
      case 'file': //文件
        try {
          wx.eventBus.trigger('receive_file', {msg: msg})
        } catch (e) {

        }
        // 其它case
      default:
        break;
    }
  },
  onsynccreateteam: function (team) {
    console.log('新建群了!!!!');
    var arr = cache.get('_team_list');
    arr.push(team);
    cache.set('_team_list', arr);
  },
  onsessions: function(ss){
    console.log('收到会话列表！！！',ss)
  },
  onupdatesession: function (ss) { // 更新会话[收到消息、发送消息、设置当前会话、重置会话未读数]
    console.log('进入IM--onupdatesession')
    console.log('currentSessionId', cache.get('currentSessionId'))
    wx.nim.resetCurrSession() // 重置当前会话后, 所有会话在收到消息之后会更新未读数
    console.log('update_ss', ss)
    console.log('ss.to', ss.to)
    console.log('userInfo.server_room', userInfo.server_room)
    // 首先更新列表
    var oldList = cache.get('_current_ss') || []
    var newList = wx.nim.mergeSessions(oldList, ss)
    cache.set('_current_ss', newList)
    // 后续再操作
    if (ss.to == userInfo.server_room) { // 客服消息
      console.log('当前模块：在线客服')
      if (cache.get('currentSessionId') == ss.id) { // 如果是当前会话，会将此会话未读数置为 0
        console.log('客服聊天窗口已打开')
        ss.unread = 0
        // 触发更新当前会话的未读
        // 再次重置一下未读
        var oldList = cache.get('_current_ss') || []
        var newList = wx.nim.mergeSessions(oldList, ss)
        cache.set('_current_ss', newList)
      }
      var csList = wx.getStorageSync('message-csList')
      var newcsList = wx.nim.mergeSessions(csList, ss)
      wx.setStorageSync('message-csList', newcsList)
      console.log('newcsList', newcsList)
      try {
        wx.eventBus.trigger('update_csList', { "csList": newcsList })
      } catch (e) {
        console.log('e',e)
      }
    } else if (ss.to == '0001') { // 通知消息
      console.log('当前模块：通知消息')
      var notifyList = wx.getStorageSync('message-orderNotifyList')
      var newnotifyList = wx.nim.mergeSessions(notifyList, ss)
      console.log('newnotifyList', newnotifyList)
      wx.setStorageSync('message-orderNotifyList', newnotifyList)
      wx.eventBus.trigger('update_orderNotifyList', { "data": newnotifyList })
    } else { // 会话消息
      // 如果是群更新，则重新获取群
      if (ss.lastMsg.type == 'notification' && ss.lastMsg.attach) {
        if (ss.lastMsg.attach.type == 'updateTeam') { // 群信息更新后判断群是否失效
          wx.nim.getTeam({
            teamId: ss.to,
            done: function(error, obj) {
              console.log('群更新');
              console.log('obj', obj)
              // 更新群列表
              var teamList = cache.get('_team_list')||[];
              var ind;
              teamList.forEach((it, index) => {
                if (it.teamId == obj.teamId) {
                  ind = index;
                }
              });
              console.log('ind', ind);
              teamList[ind] = obj;
              console.log('群更新teamList',teamList);
              cache.set('_team_list', teamList);
              let newObj = null;
              if (obj.serverCustom) {
                newObj = JSON.parse(obj.serverCustom)
              }
              if (obj.clientCustom) {
                newObj = JSON.parse(obj.clientCustom)
              }
              if (newObj && newObj.state == 1) { // 讲结束订单聚集在一起
                var finishedOrderChats = cache.get('_finished_order_chat') || []
                finishedOrderChats.push(ss.id);
                cache.set('_finished_order_chat', finishedOrderChats);
              } else {
                console.log('群')
              }
              console.log('currentSessionId',cache.get('currentSessionId'))
              console.log('ss', ss)
              if (cache.get('currentSessionId') == ss.id) { // 如果是当前会话，会将此会话未读数置为 0
                console.log('是当前会话')
                ss.unread = 0
                wx.eventBus.trigger('receive_msg', {msg: ss.lastMsg}) // 更新未读
                // 触发更新当前会话的未读
              }
              var sesstionList = wx.getStorageSync('message-sesstionList')
              console.log('old会话列表````', sesstionList)
              console.log('cache', cache)
              var newSesstionList = wx.nim.mergeSessions(sesstionList, ss)
              // console.log('newSesstionList', newSesstionList);
              // cache.set('_current_ss',newSesstionList);
              if (newSesstionList.length > sesstionList.length) { // 新增群
                var newTeamList = cache.get('_team_list');
                var arrLength = newTeamList.filter(it => {
                  return it.teamId == ss.id
                })
                if (!arrLength.length) {
                  wx.nim.getTeam({
                    teamId: ss.to, 
                    done: function(error, obj) {
                      console.log('error!!!', error);
                      console.log('obj', obj);
                      newTeamList.push(obj);
                      cache.set('_team_list', newTeamList);
                      wx.eventBus.trigger('total_update_sesstionlist', { "sesstionList": newSesstionList })
                    }
                  })
                }
              } else {
                wx.eventBus.trigger('total_update_sesstionlist', { "sesstionList": newSesstionList })
              }
              console.log('new会话列表````', newSesstionList)
            }
          })
        } else {
          console.log('currentSessionId',cache.get('currentSessionId'))
          console.log('ss', ss)
          if (cache.get('currentSessionId') == ss.id) { // 如果是当前会话，会将此会话未读数置为 0
            console.log('是当前会话')
            ss.unread = 0
            wx.eventBus.trigger('receive_msg', {msg: ss.lastMsg}) // 更新未读
            // 触发更新当前会话的未读
          }
          var sesstionList = wx.getStorageSync('message-sesstionList')
          console.log('old会话列表````', sesstionList)
          console.log('cache', cache)
          var newSesstionList = wx.nim.mergeSessions(sesstionList, ss)
          // console.log('newSesstionList', newSesstionList)
          // cache.set('_current_ss',newSesstionList);
          if (newSesstionList.length > sesstionList.length) {
            var newTeamList = cache.get('_team_list');
            var arrLength = newTeamList.filter(it => {
              return it.teamId == ss.id
            })
            if (!arrLength.length) {
              wx.nim.getTeam({
                teamId: ss.to, 
                done: function(error, obj) {
                  console.log('error!!!', error);
                  console.log('obj', obj);
                  newTeamList.push(obj);
                  cache.set('_team_list', newTeamList);
                  wx.eventBus.trigger('total_update_sesstionlist', { "sesstionList": newSesstionList })
                }
              })
            }
          } else {
            wx.eventBus.trigger('total_update_sesstionlist', { "sesstionList": newSesstionList })
          }
          console.log('new会话列表````', newSesstionList)
        }
      } else {
        console.log('currentSessionId',cache.get('currentSessionId'))
        console.log('ss', ss)
        if (cache.get('currentSessionId') == ss.id) { // 如果是当前会话，会将此会话未读数置为 0
          console.log('是当前会话')
          ss.unread = 0
          wx.eventBus.trigger('receive_msg', {msg: ss.lastMsg}) // 更新未读
          // 触发更新当前会话的未读
        }
        var sesstionList = wx.getStorageSync('message-sesstionList')
        console.log('old会话列表````', sesstionList)
        console.log('cache', cache)
        var newSesstionList = wx.nim.mergeSessions(sesstionList, ss)
        // console.log('newSesstionList', newSesstionList)
        // cache.set('_current_ss',newSesstionList);
        if (newSesstionList.length > sesstionList.length) {
          var newTeamList = cache.get('_team_list');
          var arrLength = newTeamList.filter(it => {
            return it.teamId == ss.id
          })
          if (!arrLength.length) {
            wx.nim.getTeam({
              teamId: ss.to, 
              done: function(error, obj) {
                console.log('error!!!', error);
                console.log('obj', obj);
                newTeamList.push(obj);
                cache.set('_team_list', newTeamList);
                wx.eventBus.trigger('total_update_sesstionlist', { "sesstionList": newSesstionList })
              }
            })
          }
        } else {
          wx.eventBus.trigger('total_update_sesstionlist', { "sesstionList": newSesstionList })
        }
        console.log('new会话列表````', newSesstionList)
      }

    }
  },
  onUpdateTeam: function (obj) {
    console.log('群信息更新', obj);
  },
  onRoamingMsgs: function (obj) { // 漫游消息
    // if (cache.get('_navigate_place') == 'kf') {
    //   cache.set('_navigate_place') == ''
    //   wx.navigateTo({
    //     url: '../../message/chat/chat' // 不带id为客服
    //   })
    // };
    console.log('收到漫游消息', obj);
    wx.setStorageSync(obj.sessionId, obj)
  },
  onSyncTeamMembersDone: function () {
    console.log('同步群列表完成')
  },
  onteams: function(teams) {
    console.log('收到群列表', teams)
    cache.set('_team_list', teams)
    // data.teams = nim.mergeTeams(data.teams, teams);
    // onInvalidTeams(teams.invalid);
  },
  onSysMsg: function (sysMsg) {
    console.log('收到系统通知', sysMsg)
  }
}


module.exports = {
  setOptions: function (opt){
    defOptions = { ...defOptions, ...opt }
    return this;
  },
  getOptions :function(){
    return defOptions ;
  },
  getInstance: function() {
    if (!(defOptions.account && defOptions.token)) {
      throw new Error("IM初始化必须传入对应的token和account")
      return;
    }
    console.log('account', defOptions.account)
    console.log('token', defOptions.token)
    wx.nim = SDK.NIM.getInstance({
      // debug: true,
      // appKey: 'c8705b1c5db3860ed420dd0109a57223',
      // appKey: 'e02bae855550bc06e75f6e50dc364a7a',
      // appKey: '52da4aa13804d9caa211797ec94ee289', // 测试环境的appKey
      appKey: '6cd099fa00e6c288656c9722922a6999', // 正式环境的appKey
      ntServerAddress: null,
      account: defOptions.account, // 登录的accid
      token: defOptions.token, // 登录的token
      onconnect: defOptions.onConnect,
      onwillreconnect: defOptions.onWillReconnect,
      ondisconnect: defOptions.onDisconnect,
      onerror: defOptions.onError,
      onmsg: defOptions.onMsg,
      onroamingmsgs: defOptions.onRoamingMsgs,
      onsessions: defOptions.onsessions,
      onsynccreateteam: defOptions.onsynccreateteam,
      onloginportschange: defOptions.onloginportschange,
      onupdatesession: defOptions.onupdatesession,
      onSyncTeamMembersDone: defOptions.onSyncTeamMembersDone,
      onteams: defOptions.onteams,
      onUpdateTeam: defOptions.onUpdateTeam,
      onsysmsg: defOptions.onSysMsg,
      syncSessionUnread: true,
      autoMarkRead: false
    });
    return wx.nim
  }
}